import { fileURLToPath } from 'url'
import nunjucks from 'nunjucks'
import fs from 'fs'

export const registryTemplate = function () {
    return async (ctx, next) => {
        ctx.render = function (html, obj) {
            let currentFileUrl = import.meta.url;
            // console.log(currentFileUrl);

            let viewsBaseUrl = new URL('../views', currentFileUrl);
            let viewsBasePath = fileURLToPath(viewsBaseUrl);

            let env = nunjucks.configure(viewsBasePath, { noCache: true, watch: true });
            ctx.body = env.render(html, obj)

        }

        await next()
    }
}


export const processStaticResources = function () {
    return async (ctx, next) => {
        let url = ctx.request.url;
        /*
            假设，我这里可以处理/static这个路径开头的情况的时候，能不能自己使用fs模块，返回指定资源的内容
    
        */

        if (url.startsWith('/statics')) {
            ctx.body = fs.readFileSync(`./${url}`);
        }

        console.log(url);
        await next();
    }
}